package com.ywz.common;

import com.alibaba.excel.EasyExcel;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 类描述 -> excel工具类
 *
 * @Author: ywz
 * @Date: 2025/02/27
 */
@Slf4j
public class EasyExcelUtils {

    /**
     * 方法描述 -> 默认的导入方法
     *
     * @param file 文件
     * @param clazz 数据类
     * @Author: ywz
     * @Date: 2025/02/27
     */
    public static <T> List<T> defaultRead(MultipartFile file, Class<T> clazz) {
        if (file == null || file.isEmpty() || clazz == null)
            return null;
        try {
            return EasyExcel.read(file.getInputStream()).head(clazz).sheet().doReadSync();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 方法描述 -> 默认的导出方法
     *
     * @param fileName 文件名
     * @param sheetName sheet名
     * @param list 数据列表
     * @param pojoClass 数据类
     * @param response 响应
     * @Author: ywz
     * @Date: 2025/02/27
     */
    public static ResultResp defaultWrite(String fileName, String sheetName, List<?> list, Class<?> pojoClass, HttpServletResponse response) {
        if (StringUtils.isEmpties(fileName, sheetName))
            return ResultResp.error("fileName和sheetName不能为空");
        if (list == null || list.isEmpty())
            return ResultResp.error("list不能为空");
        if (!fileName.endsWith(".xlsx"))
            fileName += ".xlsx";
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        try {
            EasyExcel.write(response.getOutputStream(), pojoClass).sheet("模板").doWrite(list);
        } catch (IOException e) {
            log.error("导出失败", e);
            return ResultResp.error("导出失败");
        }
        return null;
    }
}
